package com.dfa.nypl.common;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.xmlpull.v1.XmlPullParserException;

import android.text.style.BulletSpan;
import android.util.Log;

import com.dfa.nypl.entity.AdvocacyLetter;
import com.dfa.nypl.entity.LibraryLocation;
import com.dfa.nypl.entity.MailBody;
import com.dfa.nypl.entity.QuoteInfo;
import com.dfa.nypl.entity.TopHeadline;

public class WebService {
	public WebService() {

	}

	private static WebService singletonObject;

	public static WebService getSingletonService() {
		if (singletonObject == null) {
			singletonObject = new WebService();
		}
		return singletonObject;
	}

	public String getTotalAdvocacyLetterCount() throws IOException,
			XmlPullParserException {
		String SOAP_ACTION = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl/getTotalAdvocacyLetterCount";
		String METHOD_NAME = "getTotalAdvocacyLetterCount";
		String NAMESPACE = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl";
		String URL = "http://api.fanggle.com/server/webservices/com/tw/domain/nypl/NYPLData?wsdl";

		StringBuilder builder = new StringBuilder();

		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);

		envelope.setOutputSoapObject(request);

		AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
				URL);
		androidHttpTransport.call(SOAP_ACTION, envelope);

		SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;

		for (int i = 0; i < resultsRequestSOAP.getPropertyCount(); i++) {

			SoapPrimitive item = (SoapPrimitive) resultsRequestSOAP
					.getProperty(i);
			builder.append(item.toString());
		}

		return builder.toString();

	}

	public String getTotalDonation() throws IOException, XmlPullParserException {
		String SOAP_ACTION = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl/getTotalDonation";
		String METHOD_NAME = "getTotalDonation";
		String NAMESPACE = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl";
		String URL = "http://api.fanggle.com/server/webservices/com/tw/domain/nypl/NYPLData?wsdl";

		StringBuilder builder = new StringBuilder();

		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);

		envelope.setOutputSoapObject(request);

		AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
				URL);
		androidHttpTransport.call(SOAP_ACTION, envelope);

		SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;

		for (int i = 0; i < resultsRequestSOAP.getPropertyCount(); i++) {

			SoapPrimitive item = (SoapPrimitive) resultsRequestSOAP
					.getProperty(i);

			builder.append(item.toString());
		}

		return builder.toString();

	}

	public TopHeadline getTopHeadline() throws IOException,
			XmlPullParserException {
		String SOAP_ACTION = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl/getTopHeadlines";
		String METHOD_NAME = "getTopHeadlines";
		String NAMESPACE = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl";
		String URL = "http://api.fanggle.com/server/webservices/com/tw/domain/nypl/NYPLHeadlineServiceExternal?wsdl";

		TopHeadline entry = new TopHeadline();
		
		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);

		envelope.setOutputSoapObject(request);

		AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
				URL);
		androidHttpTransport.call(SOAP_ACTION, envelope);

		SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
		System.out.println("AXAX=" + resultsRequestSOAP.toString());
		

		if (resultsRequestSOAP != null
				&& resultsRequestSOAP.getPropertyCount() > 0) {
			SoapObject item = (SoapObject) resultsRequestSOAP.getProperty(0);
			

			String featureType = item.getProperty("featureType").toString();
			if (featureType.equals("Video")) {
				
				entry.setBody(item.getProperty("body").toString());
				entry.setEnable(item.getProperty("enabled").toString().trim()
						.equals("true") ? true : false);
				entry
						.setFeatureType(item.getProperty("featureType")
								.toString());
				entry.setTitle(item.getProperty("title").toString());
				entry.setUrl(item.getProperty("url").toString());
				entry.setYouTubeEmbeddedCode(item.getProperty(
						"youTubeEmbeddedCode").toString());

			} else if (featureType.equals("Headline")) {
				entry = new TopHeadline();
				entry.setBody(item.getProperty("body").toString());
				entry.setEnable(item.getProperty("enabled").toString().trim()
						.equals("true") ? true : false);
				entry
						.setFeatureType(item.getProperty("featureType")
								.toString());
				entry.setTitle(item.getProperty("title").toString());
				entry.setUrl(item.getProperty("url").toString());
			} else if (featureType.equals("Photo")) {
				entry = new TopHeadline();

				entry.setEnable(item.getProperty("enabled").toString().trim()
						.equals("true") ? true : false);
				entry
						.setFeatureType(item.getProperty("featureType")
								.toString());
				entry.setTitle(item.getProperty("title").toString());
				entry.setPhotoUidID(item.getProperty("photoUidID").toString());

			} else if (featureType.equals("Text")) {
				entry = new TopHeadline();
				entry.setBody(item.getProperty("body").toString());
				entry.setEnable(item.getProperty("enabled").toString().trim()
						.equals("true") ? true : false);
				entry
						.setFeatureType(item.getProperty("featureType")
								.toString());
				entry.setTitle(item.getProperty("title").toString());

			}
			
		}
		return entry;
	}

	public MailBody getMailInfo() throws IOException, XmlPullParserException {
		String SOAP_ACTION = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl/getNYPLControl";
		String METHOD_NAME = "getNYPLControl";
		String NAMESPACE = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl";
		String URL = "http://api.fanggle.com/server/webservices/com/tw/domain/nypl/NYPLControlService?wsdl";

		MailBody entry = new MailBody();

		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);

		envelope.setOutputSoapObject(request);

		AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
				URL);
		androidHttpTransport.call(SOAP_ACTION, envelope);

		SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;

		if (resultsRequestSOAP != null
				&& resultsRequestSOAP.getPropertyCount() > 0) {
			SoapObject item = (SoapObject) resultsRequestSOAP.getProperty(0);

			String mailSubject = item.getProperty("displayTextNYCSubject")
					.toString();
			String mailBody = item.getProperty("advocacyNonResidentInfoBody")
					.toString();
			entry.setMailSubject(mailSubject);
			entry.setMailBody(mailBody);

			System.out.println("::" + mailSubject + "::" + mailBody);
		}

		return entry;

	}

	public QuoteInfo getRandomQuote() throws IOException,
			XmlPullParserException {
		String SOAP_ACTION = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl/getRandomQuote";
		String METHOD_NAME = "getRandomQuote";
		String NAMESPACE = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl";
		String URL = "http://api.fanggle.com/server/webservices/com/tw/domain/nypl/NYPLUserQuoteService?wsdl";

		QuoteInfo entry = new QuoteInfo();

		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);

		envelope.setOutputSoapObject(request);

		AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
				URL);
		androidHttpTransport.call(SOAP_ACTION, envelope);

		SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;

		if (resultsRequestSOAP != null
				&& resultsRequestSOAP.getPropertyCount() > 0) {
			SoapObject item = (SoapObject) resultsRequestSOAP.getProperty(0);

			String firstName = item.getProperty("firstName").toString();
			String lastName = item.getProperty("lastName").toString();
			String userQuote = item.getProperty("userQuote").toString();

			entry.setFirstName(firstName);
			entry.setLastName(lastName);
			entry.setUserQuote(userQuote);
		}

		return entry;
	}

	public CampaignInfo getCampaignInfo() throws IOException,
			XmlPullParserException {
		String SOAP_ACTION = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl/getNYPLControl";
		String METHOD_NAME = "getNYPLControl";
		String NAMESPACE = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl";
		String URL = "http://api.fanggle.com/server/webservices/com/tw/domain/nypl/NYPLControlService?wsdl";

		CampaignInfo entry = new CampaignInfo();

		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);

		envelope.setOutputSoapObject(request);

		AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
				URL);
		androidHttpTransport.call(SOAP_ACTION, envelope);

		SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;

		if (resultsRequestSOAP != null
				&& resultsRequestSOAP.getPropertyCount() > 0) {
			SoapObject item = (SoapObject) resultsRequestSOAP.getProperty(0);

			String imageFieldId = item.getProperty("campaignImageFileId")
					.toString();
			String title = item.getProperty("title").toString();

			entry.setCampaignImageId(imageFieldId);
			entry.setCampaignTitle(title);
		}

		return entry;

	}

	public String getNYPLGoal() throws IOException, XmlPullParserException {
		String SOAP_ACTION = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl/getNYPLControl";
		String METHOD_NAME = "getNYPLControl";
		String NAMESPACE = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl";
		String URL = "http://api.fanggle.com/server/webservices/com/tw/domain/nypl/NYPLControlService?wsdl";

		StringBuilder builder = new StringBuilder();

		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);

		envelope.setOutputSoapObject(request);

		AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
				URL);
		androidHttpTransport.call(SOAP_ACTION, envelope);

		SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;

		for (int i = 0; i < resultsRequestSOAP.getPropertyCount(); i++) {

			SoapObject item = (SoapObject) resultsRequestSOAP.getProperty(i);

			builder.append(item.getProperty("advocacyGoal").toString() + ",");
			builder.append(item.getProperty("fundraisingGoal").toString());
		}

		return builder.toString();

	}

	public List<LibraryLocation> getNYPLLocationCollection()
			throws IOException, XmlPullParserException {
		String SOAP_ACTION = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl/getAllOrderByName";
		String METHOD_NAME = "getAllOrderByName";
		String NAMESPACE = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl";
		String URL = "http://api.fanggle.com/server/webservices/com/tw/domain/nypl/NYPLLibraryLocationService?wsdl";

		List<LibraryLocation> listOfLocation = new ArrayList<LibraryLocation>();

		List<AdvocacyLetter> listOfLetterCounter = WebService
				.getSingletonService()
				.getAdvocacyLetterCountForLibraryLocation();

		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);

		AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
				URL);
		androidHttpTransport.call(SOAP_ACTION, envelope);

		SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;

		for (int i = 0; i < resultsRequestSOAP.getPropertyCount(); i++) {
			LibraryLocation entry = new LibraryLocation();

			SoapObject item = (SoapObject) resultsRequestSOAP.getProperty(i);

			entry.setAddress(item.getProperty(4).toString());
			entry.setCity(item.getProperty(5).toString());
			entry.setLat(Double.parseDouble(item.getProperty(6).toString()));
			entry.setLon(Double.parseDouble(item.getProperty(7).toString()));
			entry.setName(item.getProperty(8).toString());
			entry.setState(item.getProperty(9).toString());
			int countLetter = 0;

			if (listOfLetterCounter != null && listOfLetterCounter.size() > 0) {
				for (int k = 0; k < listOfLetterCounter.size(); k++) {
					AdvocacyLetter advEntry = listOfLetterCounter.get(k);
					if (advEntry.getId().trim().equals(
							item.getProperty(1).toString().trim())) {
						countLetter = advEntry.getCount();
						break;
					}
				}
			}
			entry.setCountLetter(countLetter);

			listOfLocation.add(entry);
		}
		return listOfLocation;
	}

	public String getNYPLLibraryLocation() throws Exception {
		String SOAP_ACTION = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl/getNYPLLibraryLocation";
		String METHOD_NAME = "getNYPLLibraryLocation";
		String NAMESPACE = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl";
		String URL = "http://api.fanggle.com/server/webservices/com/tw/domain/nypl/NYPLLibraryLocationService?wsdl";

		StringBuilder builder = new StringBuilder();

		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		request.addProperty("id", "e2b45d25-0060-f010-ef63-3a4e1a118e9b");

		envelope.setOutputSoapObject(request);

		AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
				URL);
		androidHttpTransport.call(SOAP_ACTION, envelope);

		SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;

		for (int i = 0; i < resultsRequestSOAP.getPropertyCount(); i++) {

			SoapObject item = (SoapObject) resultsRequestSOAP.getProperty(i);

			builder.append(item.getProperty(4).toString() + "\n");
		}

		builder.append("Hello world");
		return builder.toString();

	}

	public String createNYPLTellAFriend(String email, String message,
			String firstName, String lastName, String sendToEmail) {
		String SOAP_ACTION = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl/createNYPLTellAFriend";
		String URL = "http://api.fanggle.com/server/webservices/com/tw/domain/nypl/NYPLTellAFriendService?wsdl";

		String envelope = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
		envelope += "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:nypl=\"http://schemas.fanggle.com/services/external/com/tw/domain/nypl\">\n";
		envelope += "<soapenv:Header/>\n";
		envelope += "<soapenv:Body>";
		envelope += "<nypl:createNYPLTellAFriend>\n";
		envelope += "<nyplTellAFriend>\n";
		envelope += "<email>%s</email>\n";
		envelope += "<firstName>%s</firstName>\n";
		envelope += "<lastName>%s</lastName>\n";
		envelope += "<message>%s</message>\n";
		envelope += "<sendToEmails>%s</sendToEmails>\n";
		envelope += "</nyplTellAFriend>\n";
		envelope += "</nypl:createNYPLTellAFriend>\n";
		envelope += "</soapenv:Body>\n";
		envelope += "</soapenv:Envelope>\n";

		String requestEnvelope = String.format(envelope, email, firstName,
				lastName, message, sendToEmail);
		System.out.println("Request=" + requestEnvelope);

		String response = CallWebService(URL, SOAP_ACTION, requestEnvelope);

		return response;
	}

	public String createNYPLAdvocacyCollectInfo(String addr1, String addr2,
			String borough, String city, String confirmEmailsOk,
			String countryCode, String email, String firstName,
			String lastName, String libraryId, String mailBody,
			String mailSigOff, String mailSubject, String phone,
			String postalCode, String state, String title) {

		boolean addressFlag = true, phoneFlag = true;

		String SOAP_ACTION = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl/createNYPLAdvocacyCollectInfo";
		String URL = "http://api.fanggle.com/server/webservices/com/tw/domain/nypl/NYPLAdvocacyCollectInfoService?wsdl";

		String envelope = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
		envelope += "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:nypl=\"http://schemas.fanggle.com/services/external/com/tw/domain/nypl\">\n";
		envelope += "<soapenv:Header/>\n";
		envelope += "<soapenv:Body>";
		envelope += "<nypl:createNYPLAdvocacyCollectInfo>\n";
		envelope += "<nyplAdvocacyCollectInfo>\n";
		envelope += "<address1>%s</address1>\n";
		if (addr2 != null && !addr2.equals("")) {
			envelope += "<address2>%s</address2>\n";
			addressFlag = false;
		}
		envelope += "<borough>%s</borough>\n";
		envelope += "<city>%s</city>\n";
		envelope += "<confirmEmailsOk>%s</confirmEmailsOk>\n";
		envelope += "<countryCode>%s</countryCode>\n";
		envelope += "<email>%s</email>\n";
		envelope += "<firstName>%s</firstName>\n";
		envelope += "<lastName>%s</lastName>\n";
		envelope += "<libraryLocationId>%s</libraryLocationId>\n";
		envelope += "<mailBody>%s</mailBody>\n";
		envelope += "<mailSignoff>%s</mailSignoff>\n	";
		envelope += "<mailSubject>%s</mailSubject>\n";
		if (phone != null && !phone.equals("")) {
			envelope += "<phone>%s</phone>\n";
			phoneFlag = false;
		}

		envelope += "<postalCode>%s</postalCode>\n";
		envelope += "<state>%s</state>\n";
		envelope += "<title>%s</title>\n";
		envelope += "</nyplAdvocacyCollectInfo>\n";
		envelope += "</nypl:createNYPLAdvocacyCollectInfo>\n";
		envelope += "</soapenv:Body>\n";
		envelope += "</soapenv:Envelope>\n";

		String requestEnvelope = "";
		if (addressFlag && phoneFlag) {
			requestEnvelope = String.format(envelope, addr1, borough, city,
					confirmEmailsOk, countryCode, email, firstName, lastName,
					libraryId, mailBody, mailSigOff, mailSubject, postalCode,
					state, title);
		} else if (addressFlag && !phoneFlag) {
			requestEnvelope = String.format(envelope, addr1, borough, city,
					confirmEmailsOk, countryCode, email, firstName, lastName,
					libraryId, mailBody, mailSigOff, mailSubject, phone,
					postalCode, state, title);

		} else if (!addressFlag && phoneFlag) {
			requestEnvelope = String.format(envelope, addr1, addr2, borough,
					city, confirmEmailsOk, countryCode, email, firstName,
					lastName, libraryId, mailBody, mailSigOff, mailSubject,
					postalCode, state, title);
		} else {
			requestEnvelope = String.format(envelope, addr1, addr2, borough,
					city, confirmEmailsOk, countryCode, email, firstName,
					lastName, libraryId, mailBody, mailSigOff, mailSubject,
					phone, postalCode, state, title);
		}

		String response = CallWebService(URL, SOAP_ACTION, requestEnvelope);

		System.out.println("RESPONSE=" + response);
		return response;

	}

	public List<AdvocacyLetter> getAdvocacyLetterCountForLibraryLocation()
			throws IOException, XmlPullParserException {
		String SOAP_ACTION = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl/getAdvocacyLetterCountForLibraryLocations";
		String METHOD_NAME = "getAdvocacyLetterCountForLibraryLocations";
		String NAMESPACE = "http://schemas.fanggle.com/services/external/com/tw/domain/nypl";
		String URL = "http://api.fanggle.com/server/webservices/com/tw/domain/nypl/NYPLData?wsdl";

		List<AdvocacyLetter> listOfLetters = new ArrayList<AdvocacyLetter>();

		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);

		AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
				URL);
		androidHttpTransport.call(SOAP_ACTION, envelope);

		SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;

		for (int i = 0; i < resultsRequestSOAP.getPropertyCount(); i++) {
			AdvocacyLetter entry = new AdvocacyLetter();

			SoapObject item = (SoapObject) resultsRequestSOAP.getProperty(i);
			entry.setCount(Integer.parseInt(item.getProperty(0).toString()));
			entry.setId(item.getProperty(1).toString());

			listOfLetters.add(entry);

		}

		return listOfLetters;

	}

	private String CallWebService(String url, String soapAction, String envelope) {
		final DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 15000);
		HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

		HttpPost httppost = new HttpPost(url);
		httppost.setHeader("soapaction", soapAction);
		httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

		String responseString = "";
		try {

			HttpEntity entity = new StringEntity(envelope);
			httppost.setEntity(entity);

			ResponseHandler<String> rh = new ResponseHandler<String>() {
				public String handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {

					HttpEntity entity = response.getEntity();

					StringBuffer out = new StringBuffer();
					byte[] b = EntityUtils.toByteArray(entity);

					out.append(new String(b, 0, b.length));
					return out.toString();
				}
			};

			responseString = httpClient.execute(httppost, rh);

		} catch (Exception e) {
			Log.v("exception", e.toString());
		}

		httpClient.getConnectionManager().shutdown();
		return responseString;
	}

}
